package com.pinyoumei.app.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Outline;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.LuckPanActivity;
import com.pinyoumei.app.activity.PTOrderSelectActivity;
import com.pinyoumei.app.activity.ProductDetailActivity;
import com.pinyoumei.app.activity.ProductDetailPtActivity;
import com.pinyoumei.app.activity.ShoppingCenter.ShopSearchActivity;
import com.pinyoumei.app.activity.SignInActivity;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.activity.integral.IntegralDetailActivity;
import com.pinyoumei.app.activity.integral.IntegralShopActivity;
import com.pinyoumei.app.adapter.BottomFirstAdapter;
import com.pinyoumei.app.adapter.BottomFirstNewAdapter;
import com.pinyoumei.app.adapter.FirstPTAdapter;
import com.pinyoumei.app.adapter.FirstPTNewAdapter;
import com.pinyoumei.app.adapter.GoodsTypeAdapter;
import com.pinyoumei.app.adapter.SecondTopAdapter;
import com.pinyoumei.app.adapter.TopFirstAdapter;
import com.pinyoumei.app.adapter.TopFirstNewAdapter;
import com.pinyoumei.app.bean.FirstBean;
import com.pinyoumei.app.bean.FirstNewBean;
import com.pinyoumei.app.bean.FirstloadBean;
import com.pinyoumei.app.bean.FirstloadNewBean;
import com.pinyoumei.app.bean.GoodDetailsBean;
import com.pinyoumei.app.bean.GoodsTypeBean;
import com.pinyoumei.app.bean.IntegralDetailsBean;
import com.pinyoumei.app.bean.SectionBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.IntentUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.SlidingTabLayout;
import com.pinyoumei.app.view.WrapContentHeightViewPager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressLint("ValidFragment")
public class FirstFragmentNew extends BaseLazyLoadFragment implements View.OnClickListener, ViewPager.OnPageChangeListener {
    private String mTitle;
    private Banner banner;
    private int page = 1;
    private LoadingDailog loadingDailog;
    private Gson gson;
    private TopFirstNewAdapter topFirstAdapter;
    private FirstPTNewAdapter ptAdapter;

    private TextView tv_continue_sign_day;
    private TextView tv_total_sign_day;
    private String sId = "";
    List<GoodsTypeBean.GoodsTypeDto> goodsTypeDtos = new ArrayList<>();
    private View rootView;

    public static FirstFragmentNew getInstance(String title) {
        FirstFragmentNew sf = new FirstFragmentNew();
        sf.mTitle = title;
        return sf;
    }


    private List<String> image_list = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_first_new;
    }

    @Override
    public void initView(View rootView) {
        this.rootView = rootView;
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();
        tv_continue_sign_day = rootView.findViewById(R.id.tv_continue_sign_day);
        tv_total_sign_day = rootView.findViewById(R.id.tv_total_sign_day);
        RelativeLayout rl_luck = rootView.findViewById(R.id.rl_luck);
        rl_luck.setOnClickListener(this);
        RelativeLayout rl_sign_in = rootView.findViewById(R.id.rl_sign_in);
        rl_sign_in.setOnClickListener(this);
        RelativeLayout rl_search = rootView.findViewById(R.id.rl_search);
        rl_search.setOnClickListener(this);
        TextView integralGoods = rootView.findViewById(R.id.integral_goods);
        integralGoods.setOnClickListener(this);
        RecyclerView rv_top = rootView.findViewById(R.id.rv_top);
        rv_top.setLayoutManager(new GridLayoutManager(getActivity(), 5, GridLayoutManager.VERTICAL, false));
        topFirstAdapter = new TopFirstNewAdapter(R.layout.item_first_top, null);
        topFirstAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rv_top.setAdapter(topFirstAdapter);
//        goodsTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                sId = sectionDtos.get(position).getId();
//                for (int i=0;i<sectionDtos.size();i++){
//                    sectionDtos.get(i).setSelect(false);
//                }
//                sectionDtos.get(position).setSelect(true);
//                goodsTypeAdapter.notifyDataSetChanged();
//                listBeans.clear();
//                bottomFirstAdapter.notifyDataSetChanged();
//                page = 1;
//                LoadMoreData();
//            }
//        });
        topFirstAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (topFirstAdapter.getData() != null && topFirstAdapter.getData().size() > 0) {
                    if (topFirstAdapter.getData().get(position).getIs_open() == 0) {
                        Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
                    } else {
                        if (topFirstAdapter.getData().get(position).getIs_h5_view() == 1) {
                            Intent intent = new Intent(getActivity(), WebViewActivity.class);
                            intent.putExtra("order_title", topFirstAdapter.getData().get(position).getModel_name());
                            intent.putExtra("url", topFirstAdapter.getData().get(position).getH5_url());
                            startActivity(intent);
                        } else {
                            //跳转
                            IntentUtils.Intent_to(getActivity(), topFirstAdapter.getData().get(position).getModel_method(),topFirstAdapter.getData().get(position).getModel_name());
                        }
                    }
                }
            }
        });



        banner = rootView.findViewById(R.id.banner);

        RecyclerView rv_pt = rootView.findViewById(R.id.rv_pt);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_pt.setLayoutManager(manager);
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(rv_pt);

        ptAdapter = new FirstPTNewAdapter(R.layout.item_first_pt, null);
        ptAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rv_pt.setAdapter(ptAdapter);
        ptAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                scoreIndexGoodsDetail(ptAdapter.getData().get(position).getId());
            }
        });



        SmartRefreshLayout smartRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                EventBusUtils.post("++");
                page++;
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                EventBusUtils.post("==");
                mTab.setCurrentTab(0);
                page = 1;
                InitData();
                goodsListType();
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
        InitData();
        goodsListType();
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("type", 1);
        map.put("version_num", Utils.getVersionCode(getActivity()));

        OkGo.<String>post(Constants.HOME_DATA_NEW)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("type", 1)
                .params("version_num", Utils.getVersionCode(getActivity()))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        FirstNewBean firstBean = gson.fromJson(response.body(), FirstNewBean.class);

                        if (firstBean.getCode() >= 0) {

                            if(firstBean.getResult().getHome_icon_list() != null) {
                                topFirstAdapter.setNewData(firstBean.getResult().getHome_icon_list());
                            }
                            if(firstBean.getResult().getHome_banner_list() != null) {
                                initBanner(firstBean.getResult().getHome_banner_list());
                            }
                            if(firstBean.getResult().getScore_goods_list() != null) {
                                ptAdapter.setNewData(firstBean.getResult().getScore_goods_list());
                            }
                            tv_continue_sign_day.setText(firstBean.getResult().getContinue_sign_day()+"次");
                            tv_total_sign_day.setText(firstBean.getResult().getTotal_sign_day()+"次");

                        } else {
                            Toast.makeText(getActivity(), firstBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }


    private void initBanner(List<FirstNewBean.ResultBean.HomeBannerListBean> home_banner_list) {
        //第二个Banner
        image_list.clear();
        if (home_banner_list!=null && home_banner_list.size()>0){
            for (int i = 0; i < home_banner_list.size(); i++) {
                image_list.add(home_banner_list.get(i).getImg_path());
            }

            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置Banner的样式BannerConfig.CIRCLE_INDICATOR


            banner.setImages(image_list); //存放图片的list集合url
            banner.setBannerAnimation(Transformer.ZoomOutSlide);//设置Banner轮播的动画特效的样式
            //banner.setPageTransformer(true,)//自定义轮播动画
            banner.setImageLoader(new GlideImageLoader());//设置图片加载器
            banner.isAutoPlay(true);//设置默认为自动轮播
            banner.setDelayTime(3000);//设置轮播间隔时间
            //设置指示器位置（当banner模式中有指示器时）
            banner.setIndicatorGravity(BannerConfig.CENTER);

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (home_banner_list.get(position).getIs_can_link() == 1) {

                        if (home_banner_list.get(position).getIs_h5() == 1) {
                            Intent intent = new Intent(getActivity(), WebViewActivity.class);
                            intent.putExtra("url", home_banner_list.get(position).getH5_url());
                            intent.putExtra("order_title", "");
                            startActivity(intent);
                        } else {
                            IntentUtils.Intent_to(getActivity(), home_banner_list.get(position).getMethod_name()
                                    ,"");
                        }

                    }
                }

            });

            banner.start();

        }



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.rl_luck:
        		startActivity(new Intent(getActivity(), LuckPanActivity.class));
        		break;

        		case R.id.rl_sign_in:
                    //签到
        		startActivity(new Intent(getActivity(), SignInActivity.class));
        		break;

        		case R.id.rl_search:
        		startActivity(new Intent(getActivity(), ShopSearchActivity.class));
        		break;
            case R.id.integral_goods:
                //积分
                startActivity(new Intent(getActivity(), IntegralShopActivity.class));
                break;
        	default:
        		break;
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        mViewPager.resetHeight(i);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    //使用Glide加载器
    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {

            //Glide 加载图片

//            Glide.with(context).load(path).into(imageView);

            //设置图片圆角角度
            RoundedCorners roundedCorners = new RoundedCorners(DensityUtil.dp2px(5));
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
            Glide.with(context)
                    .load(path)
                    .apply(options)
                    .into(imageView);

        }
    }

    private void InitGoodDate(String goods_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("goods_id", goods_id);


        OkGo.<String>post(Constants.GOODS_LIST_DETAIL)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("goods_id", goods_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        GoodDetailsBean goodDetailsBean = gson.fromJson(response.body(), GoodDetailsBean.class);

                        if (goodDetailsBean.getCode() >= 0) {
                            Utils.isActivity = "2";
                            if (goodDetailsBean.getResult().getData_info().getIs_can_pt() == 1) {
                                Intent intent = new Intent(getActivity(), ProductDetailPtActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            }

                        } else {
                            Toast.makeText(getActivity(), goodDetailsBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    private void goodsListType() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        OkGo.<String>post(Constants.goodsListType)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        GoodsTypeBean bean = gson.fromJson(response.body(), GoodsTypeBean.class);
                        if (bean == null){
                            return;
                        }
                        if (bean.getCode() >= 0) {
                            goodsTypeDtos.clear();
                            goodsTypeDtos = bean.getResult().getGoods_type_list();
                            initViewPager(goodsTypeDtos);
                        } else {
                            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                });


    }

    SlidingTabLayout mTab;

    WrapContentHeightViewPager mViewPager;


    private void initViewPager(List<GoodsTypeBean.GoodsTypeDto> sectionDtos){

        mTab = rootView.findViewById(R.id.tab_fragment);
        mViewPager = rootView.findViewById(R.id.viewpager_fragment);

        MyPagerAdapter mAdapter = new MyPagerAdapter(sectionDtos,getActivity().getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mTab.setViewPager(mViewPager);
        mViewPager.setOffscreenPageLimit(sectionDtos.size());
        mViewPager.setCurrentItem(0);
        mViewPager.addOnPageChangeListener(this);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        List<GoodsTypeBean.GoodsTypeDto> sectionDtos;
        public MyPagerAdapter(List<GoodsTypeBean.GoodsTypeDto> sectionDtos,FragmentManager fm) {
            super(fm);
            this.sectionDtos = sectionDtos;
        }

        @Override
        public int getCount() {
            return sectionDtos.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return sectionDtos.get(position).getType_name();
        }

        @Override
        public Fragment getItem(int position) {
            GoodsIndexFragment fragment = new GoodsIndexFragment(mViewPager,position);
            Bundle bundle = new Bundle();
            bundle.putString("position", sectionDtos.get(position).getId());
            bundle.putString("title", sectionDtos.get(position).getType_name());
            fragment.setArguments(bundle);
            return fragment;
        }
    }

    private void scoreIndexGoodsDetail(String goods_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getContext()));
        map.put("goods_id", goods_id);

        OkGo.<String>post(Constants.scoreIndexGoodsDetail)
                .params("user_id", SPUtils.getAppUserId(getContext()))
                .params("goods_id", goods_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        IntegralDetailsBean integralDetailsBean = gson.fromJson(response.body(), IntegralDetailsBean.class);

                        if (integralDetailsBean.getCode() >= 0) {
                            Intent intent = new Intent(getContext(), IntegralDetailActivity.class);
                            intent.putExtra("integralDetailsBean", integralDetailsBean);
                            intent.putExtra("goods_id", goods_id);
                            startActivity(intent);
                        } else {
                            Toast.makeText(getContext(), integralDetailsBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }



}